{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "pycharm-f7427e7c",
   "display_name": "PyCharm (pythonProject)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "source": [
    "<center><h1>第五章 变形</h1></center>"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "source": [
    "## 一、长宽表的变形\n",
    "\n",
    "什么是长表？什么是宽表？这个概念是对于某一个特征而言的。例如：一个表中把性别存储在某一个列中，那么它就是关于性别的长表；如果把性别作为列名，列中的元素是某一其他的相关特征数值，那么这个表是关于性别的宽表。下面的两张表就分别是关于性别的长表和宽表："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "  Gender  Height\n",
       "0      F     163\n",
       "1      F     160\n",
       "2      M     175\n",
       "3      M     180"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Gender</th>\n      <th>Height</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>F</td>\n      <td>163</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>F</td>\n      <td>160</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>M</td>\n      <td>175</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>M</td>\n      <td>180</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 2
    }
   ],
   "source": [
    "pd.DataFrame({'Gender':['F','F','M','M'], 'Height':[163, 160, 175, 180]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "   Height: F  Height: M\n",
       "0        163        175\n",
       "1        160        180"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Height: F</th>\n      <th>Height: M</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>163</td>\n      <td>175</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>160</td>\n      <td>180</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 3
    }
   ],
   "source": [
    "pd.DataFrame({'Height: F':[163, 160], 'Height: M':[175, 180]})"
   ]
  },
  {
   "source": [
    "显然这两张表从信息上是完全等价的，它们包含相同的身高统计数值，只是这些数值的呈现方式不同，而其呈现方式主要又与性别一列选择的布局模式有关，即到底是以$\\color{red}{long}$的状态存储还是以$\\color{red}{wide}$的状态存储。因此，`pandas`针对此类长宽表的变形操作设计了一些有关的变形函数。\n",
    "\n",
    "### 1. pivot\n",
    "\n",
    "`pivot`是一种典型的长表变宽表的函数，首先来看一个例子：下表存储了张三和李四的语文和数学分数，现在想要把语文和数学分数作为列来展示。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "   Class       Name  Subject  Grade\n",
       "0      1  San Zhang  Chinese     80\n",
       "1      1  San Zhang     Math     75\n",
       "2      2      Si Li  Chinese     90\n",
       "3      2      Si Li     Math     85"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Class</th>\n      <th>Name</th>\n      <th>Subject</th>\n      <th>Grade</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Chinese</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Math</td>\n      <td>75</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Chinese</td>\n      <td>90</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Math</td>\n      <td>85</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 4
    }
   ],
   "source": [
    "df = pd.DataFrame({'Class':[1,1,2,2],\n",
    "                   'Name':['San Zhang','San Zhang','Si Li','Si Li'],\n",
    "                   'Subject':['Chinese','Math','Chinese','Math'],\n",
    "                   'Grade':[80,75,90,85]})\n",
    "df"
   ]
  },
  {
   "source": [
    "对于一个基本的长变宽操作而言，最重要的有三个要素，分别是变形后的行索引、需要转到列索引的列，以及这些列和行索引对应的数值，它们分别对应了`pivot`方法中的`index, columns, values`参数。新生成表的列索引是`columns`对应列的`unique`值，而新表的行索引是`index`对应列的`unique`值，而`values`对应了想要展示的数值列。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "Subject    Chinese  Math\n",
       "Name                    \n",
       "San Zhang       80    75\n",
       "Si Li           90    85"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Subject</th>\n      <th>Chinese</th>\n      <th>Math</th>\n    </tr>\n    <tr>\n      <th>Name</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>San Zhang</th>\n      <td>80</td>\n      <td>75</td>\n    </tr>\n    <tr>\n      <th>Si Li</th>\n      <td>90</td>\n      <td>85</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 5
    }
   ],
   "source": [
    "df.pivot(index='Name', columns='Subject', values='Grade')"
   ]
  },
  {
   "source": [
    "通过颜色的标记，更容易地能够理解其变形的过程：\n",
    "\n",
    "<img src=\"../source/_static/ch5_pivot.png\" width=\"20%\">"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "利用`pivot`进行变形操作需要满足唯一性的要求，即由于在新表中的行列索引对应了唯一的`value`，因此原表中的`index`和`columns`对应两个列的行组合必须唯一。例如，现在把原表中第二行张三的数学改为语文就会报错，这是由于`Name`与`Subject`的组合中两次出现`(\"San Zhang\", \"Chinese\")`，从而最后不能够确定到底变形后应该是填写80分还是75分。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "ValueError('Index contains duplicate entries, cannot reshape')"
      ]
     },
     "metadata": {},
     "execution_count": 6
    }
   ],
   "source": [
    "df.loc[1, 'Subject'] = 'Chinese'\n",
    "try:\n",
    "    df.pivot(index='Name', columns='Subject', values='Grade')\n",
    "except Exception as e:\n",
    "    Err_Msg = e\n",
    "Err_Msg"
   ]
  },
  {
   "source": [
    "`pandas`从`1.1.0`开始，`pivot`相关的三个参数允许被设置为列表，这也意味着会返回多级索引。这里构造一个相应的例子来说明如何使用：下表中六列分别为班级、姓名、测试类型（期中考试和期末考试）、科目、成绩、排名。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "   Class       Name Examination  Subject  Grade  rank\n",
       "0      1  San Zhang         Mid  Chinese     80    10\n",
       "1      1  San Zhang       Final  Chinese     75    15\n",
       "2      2      Si Li         Mid  Chinese     85    21\n",
       "3      2      Si Li       Final  Chinese     65    15\n",
       "4      1  San Zhang         Mid     Math     90    20\n",
       "5      1  San Zhang       Final     Math     85     7\n",
       "6      2      Si Li         Mid     Math     92     6\n",
       "7      2      Si Li       Final     Math     88     2"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Class</th>\n      <th>Name</th>\n      <th>Examination</th>\n      <th>Subject</th>\n      <th>Grade</th>\n      <th>rank</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Mid</td>\n      <td>Chinese</td>\n      <td>80</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Final</td>\n      <td>Chinese</td>\n      <td>75</td>\n      <td>15</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Mid</td>\n      <td>Chinese</td>\n      <td>85</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Final</td>\n      <td>Chinese</td>\n      <td>65</td>\n      <td>15</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Mid</td>\n      <td>Math</td>\n      <td>90</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Final</td>\n      <td>Math</td>\n      <td>85</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Mid</td>\n      <td>Math</td>\n      <td>92</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Final</td>\n      <td>Math</td>\n      <td>88</td>\n      <td>2</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 7
    }
   ],
   "source": [
    "df = pd.DataFrame({'Class':[1, 1, 2, 2, 1, 1, 2, 2],\n",
    "                   'Name':['San Zhang', 'San Zhang', 'Si Li', 'Si Li',\n",
    "                              'San Zhang', 'San Zhang', 'Si Li', 'Si Li'],\n",
    "                   'Examination': ['Mid', 'Final', 'Mid', 'Final',\n",
    "                                    'Mid', 'Final', 'Mid', 'Final'],\n",
    "                   'Subject':['Chinese', 'Chinese', 'Chinese', 'Chinese',\n",
    "                                 'Math', 'Math', 'Math', 'Math'],\n",
    "                   'Grade':[80, 75, 85, 65, 90, 85, 92, 88],\n",
    "                   'rank':[10, 15, 21, 15, 20, 7, 6, 2]})\n",
    "df"
   ]
  },
  {
   "source": [
    "现在想要把测试类型和科目联合组成的四个类别（期中语文、期末语文、期中数学、期末数学）转到列索引，并且同时统计成绩和排名："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "                  Grade                     rank                 \n",
       "Subject         Chinese       Math       Chinese       Math      \n",
       "Examination         Mid Final  Mid Final     Mid Final  Mid Final\n",
       "Class Name                                                       \n",
       "1     San Zhang      80    75   90    85      10    15   20     7\n",
       "2     Si Li          85    65   92    88      21    15    6     2"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n\n    .dataframe thead tr:last-of-type th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th></th>\n      <th colspan=\"4\" halign=\"left\">Grade</th>\n      <th colspan=\"4\" halign=\"left\">rank</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>Subject</th>\n      <th colspan=\"2\" halign=\"left\">Chinese</th>\n      <th colspan=\"2\" halign=\"left\">Math</th>\n      <th colspan=\"2\" halign=\"left\">Chinese</th>\n      <th colspan=\"2\" halign=\"left\">Math</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>Examination</th>\n      <th>Mid</th>\n      <th>Final</th>\n      <th>Mid</th>\n      <th>Final</th>\n      <th>Mid</th>\n      <th>Final</th>\n      <th>Mid</th>\n      <th>Final</th>\n    </tr>\n    <tr>\n      <th>Class</th>\n      <th>Name</th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <th>San Zhang</th>\n      <td>80</td>\n      <td>75</td>\n      <td>90</td>\n      <td>85</td>\n      <td>10</td>\n      <td>15</td>\n      <td>20</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <th>Si Li</th>\n      <td>85</td>\n      <td>65</td>\n      <td>92</td>\n      <td>88</td>\n      <td>21</td>\n      <td>15</td>\n      <td>6</td>\n      <td>2</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 8
    }
   ],
   "source": [
    "pivot_multi = df.pivot(index = ['Class', 'Name'],\n",
    "                       columns = ['Subject','Examination'],\n",
    "                       values = ['Grade','rank'])\n",
    "pivot_multi"
   ]
  },
  {
   "source": [
    "根据唯一性原则，新表的行索引等价于对`index`中的多列使用`drop_duplicates`，而列索引的长度为`values`中的元素个数乘以`columns`的唯一组合数量（与`index`类似） 。从下面的示意图中能够比较容易地理解相应的操作：\n",
    "\n",
    "<img src=\"../source/_static/ch5_mulpivot.png\" width=\"35%\">\n",
    "\n",
    "### 2. pivot_table\n",
    "\n",
    "`pivot`的使用依赖于唯一性条件，那如果不满足唯一性条件，那么必须通过聚合操作使得相同行列组合对应的多个值变为一个值。例如，张三和李四都参加了两次语文考试和数学考试，按照学院规定，最后的成绩是两次考试分数的平均值，此时就无法通过`pivot`函数来完成。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        Name  Subject  Grade\n",
       "0  San Zhang  Chinese     80\n",
       "1  San Zhang  Chinese     90\n",
       "2  San Zhang     Math    100\n",
       "3  San Zhang     Math     90\n",
       "4      Si Li  Chinese     70\n",
       "5      Si Li  Chinese     80\n",
       "6      Si Li     Math     85\n",
       "7      Si Li     Math     95"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Name</th>\n      <th>Subject</th>\n      <th>Grade</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>San Zhang</td>\n      <td>Chinese</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>San Zhang</td>\n      <td>Chinese</td>\n      <td>90</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>San Zhang</td>\n      <td>Math</td>\n      <td>100</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>San Zhang</td>\n      <td>Math</td>\n      <td>90</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Si Li</td>\n      <td>Chinese</td>\n      <td>70</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>Si Li</td>\n      <td>Chinese</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>Si Li</td>\n      <td>Math</td>\n      <td>85</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>Si Li</td>\n      <td>Math</td>\n      <td>95</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 9
    }
   ],
   "source": [
    "df = pd.DataFrame({'Name':['San Zhang', 'San Zhang', \n",
    "                              'San Zhang', 'San Zhang',\n",
    "                              'Si Li', 'Si Li', 'Si Li', 'Si Li'],\n",
    "                   'Subject':['Chinese', 'Chinese', 'Math', 'Math',\n",
    "                                 'Chinese', 'Chinese', 'Math', 'Math'],\n",
    "                   'Grade':[80, 90, 100, 90, 70, 80, 85, 95]})\n",
    "df"
   ]
  },
  {
   "source": [
    "`pandas`中提供了`pivot_table`来实现，其中的`aggfunc`参数就是使用的聚合函数。上述场景可以如下写出："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "Subject    Chinese  Math\n",
       "Name                    \n",
       "San Zhang       85    95\n",
       "Si Li           75    90"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Subject</th>\n      <th>Chinese</th>\n      <th>Math</th>\n    </tr>\n    <tr>\n      <th>Name</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>San Zhang</th>\n      <td>85</td>\n      <td>95</td>\n    </tr>\n    <tr>\n      <th>Si Li</th>\n      <td>75</td>\n      <td>90</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 10
    }
   ],
   "source": [
    "df.pivot_table(index = 'Name',\n",
    "               columns = 'Subject',\n",
    "               values = 'Grade',\n",
    "               aggfunc = 'mean')"
   ]
  },
  {
   "source": [
    "这里传入`aggfunc`包含了上一章中介绍的所有合法聚合字符串，此外还可以传入以序列为输入标量为输出的聚合函数来实现自定义操作，上述功能可以等价写出："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "Subject    Chinese  Math\n",
       "Name                    \n",
       "San Zhang       85    95\n",
       "Si Li           75    90"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Subject</th>\n      <th>Chinese</th>\n      <th>Math</th>\n    </tr>\n    <tr>\n      <th>Name</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>San Zhang</th>\n      <td>85</td>\n      <td>95</td>\n    </tr>\n    <tr>\n      <th>Si Li</th>\n      <td>75</td>\n      <td>90</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 11
    }
   ],
   "source": [
    "df.pivot_table(index = 'Name',\n",
    "               columns = 'Subject',\n",
    "               values = 'Grade',\n",
    "               aggfunc = lambda x:x.mean())"
   ]
  },
  {
   "source": [
    "此外，`pivot_table`具有边际汇总的功能，可以通过设置`margins=True`来实现，其中边际的聚合方式与`aggfunc`中给出的聚合方法一致。下面就分别统计了语文均分和数学均分、张三均分和李四均分，以及总体所有分数的均分："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "Subject    Chinese  Math    All\n",
       "Name                           \n",
       "San Zhang       85  95.0  90.00\n",
       "Si Li           75  90.0  82.50\n",
       "All             80  92.5  86.25"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Subject</th>\n      <th>Chinese</th>\n      <th>Math</th>\n      <th>All</th>\n    </tr>\n    <tr>\n      <th>Name</th>\n      <th></th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>San Zhang</th>\n      <td>85</td>\n      <td>95.0</td>\n      <td>90.00</td>\n    </tr>\n    <tr>\n      <th>Si Li</th>\n      <td>75</td>\n      <td>90.0</td>\n      <td>82.50</td>\n    </tr>\n    <tr>\n      <th>All</th>\n      <td>80</td>\n      <td>92.5</td>\n      <td>86.25</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 12
    }
   ],
   "source": [
    "df.pivot_table(index = 'Name',\n",
    "               columns = 'Subject',\n",
    "               values = 'Grade',\n",
    "               aggfunc='mean',\n",
    "               margins=True)"
   ]
  },
  {
   "source": [
    "#### 【练一练】\n",
    "在上面的边际汇总例子中，行或列的汇总为新表中行元素或者列元素的平均值，而总体的汇总为新表中四个元素的平均值。这种关系一定成立吗？若不成立，请给出一个例子来说明。\n",
    "#### 【END】\n",
    "### 3. melt\n",
    "\n",
    "长宽表只是数据呈现方式的差异，但其包含的信息量是等价的，前面提到了利用`pivot`把长表转为宽表，那么就可以通过相应的逆操作把宽表转为长表，`melt`函数就起到了这样的作用。在下面的例子中，`Subject`以列索引的形式存储，现在想要将其压缩到一个列中。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "   Class       Name  Chinese  Math\n",
       "0      1  San Zhang       80    80\n",
       "1      2      Si Li       90    75"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Class</th>\n      <th>Name</th>\n      <th>Chinese</th>\n      <th>Math</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>80</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>90</td>\n      <td>75</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 13
    }
   ],
   "source": [
    "df = pd.DataFrame({'Class':[1,2],\n",
    "                   'Name':['San Zhang', 'Si Li'],\n",
    "                   'Chinese':[80, 90],\n",
    "                   'Math':[80, 75]})\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "   Class       Name  Subject  Grade\n",
       "0      1  San Zhang  Chinese     80\n",
       "1      2      Si Li  Chinese     90\n",
       "2      1  San Zhang     Math     80\n",
       "3      2      Si Li     Math     75"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Class</th>\n      <th>Name</th>\n      <th>Subject</th>\n      <th>Grade</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Chinese</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Chinese</td>\n      <td>90</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Math</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Math</td>\n      <td>75</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 14
    }
   ],
   "source": [
    "df_melted = df.melt(id_vars = ['Class', 'Name'],\n",
    "                    value_vars = ['Chinese', 'Math'],\n",
    "                    var_name = 'Subject',\n",
    "                    value_name = 'Grade')\n",
    "df_melted"
   ]
  },
  {
   "source": [
    "`melt`的主要参数和压缩的过程如下图所示：\n",
    "\n",
    "<img src=\"../source/_static/ch5_melt.png\" width=\"35%\">\n",
    "\n",
    "前面提到了`melt`和`pivot`是一组互逆过程，那么就一定可以通过`pivot`操作把`df_melted`转回`df`的形式："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "Subject          Chinese  Math\n",
       "Class Name                    \n",
       "1     San Zhang       80    80\n",
       "2     Si Li           90    75"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Subject</th>\n      <th>Chinese</th>\n      <th>Math</th>\n    </tr>\n    <tr>\n      <th>Class</th>\n      <th>Name</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>1</th>\n      <th>San Zhang</th>\n      <td>80</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <th>Si Li</th>\n      <td>90</td>\n      <td>75</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 15
    }
   ],
   "source": [
    "df_unmelted = df_melted.pivot(index = ['Class', 'Name'],\n",
    "                              columns='Subject',\n",
    "                              values='Grade')\n",
    "df_unmelted # 下面需要恢复索引，并且重命名列索引名称"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "metadata": {},
     "execution_count": 16
    }
   ],
   "source": [
    "df_unmelted = df_unmelted.reset_index().rename_axis(columns={'Subject':''})\n",
    "df_unmelted.equals(df)"
   ]
  },
  {
   "source": [
    "### 4. wide_to_long\n",
    "\n",
    "`melt`方法中，在列索引中被压缩的一组值对应的列元素只能代表同一层次的含义，即`values_name`。现在如果列中包含了交叉类别，比如期中期末的类别和语文数学的类别，那么想要把`values_name`对应的`Grade`扩充为两列分别对应语文分数和数学分数，只把期中期末的信息压缩，这种需求下就要使用`wide_to_long`函数来完成。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "   Class       Name  Chinese_Mid  Math_Mid  Chinese_Final  Math_Final\n",
       "0      1  San Zhang           80        90             80          90\n",
       "1      2      Si Li           75        85             75          85"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Class</th>\n      <th>Name</th>\n      <th>Chinese_Mid</th>\n      <th>Math_Mid</th>\n      <th>Chinese_Final</th>\n      <th>Math_Final</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>80</td>\n      <td>90</td>\n      <td>80</td>\n      <td>90</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>75</td>\n      <td>85</td>\n      <td>75</td>\n      <td>85</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 17
    }
   ],
   "source": [
    "df = pd.DataFrame({'Class':[1,2],'Name':['San Zhang', 'Si Li'],\n",
    "                   'Chinese_Mid':[80, 75], 'Math_Mid':[90, 85],\n",
    "                   'Chinese_Final':[80, 75], 'Math_Final':[90, 85]})\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "                             Chinese  Math\n",
       "Class Name      Examination               \n",
       "1     San Zhang Mid               80    90\n",
       "                Final             80    90\n",
       "2     Si Li     Mid               75    85\n",
       "                Final             75    85"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>Chinese</th>\n      <th>Math</th>\n    </tr>\n    <tr>\n      <th>Class</th>\n      <th>Name</th>\n      <th>Examination</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">1</th>\n      <th rowspan=\"2\" valign=\"top\">San Zhang</th>\n      <th>Mid</th>\n      <td>80</td>\n      <td>90</td>\n    </tr>\n    <tr>\n      <th>Final</th>\n      <td>80</td>\n      <td>90</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">2</th>\n      <th rowspan=\"2\" valign=\"top\">Si Li</th>\n      <th>Mid</th>\n      <td>75</td>\n      <td>85</td>\n    </tr>\n    <tr>\n      <th>Final</th>\n      <td>75</td>\n      <td>85</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 18
    }
   ],
   "source": [
    "pd.wide_to_long(df,\n",
    "                stubnames=['Chinese', 'Math'],\n",
    "                i = ['Class', 'Name'],\n",
    "                j='Examination',\n",
    "                sep='_',\n",
    "                suffix='.+')"
   ]
  },
  {
   "source": [
    "具体的变换过程由下图进行展示，属相同概念的元素使用了一致的颜色标出：\n",
    "\n",
    "<img src=\"../source/_static/ch5_wtl.png\" width=\"35%\">\n",
    "\n",
    "下面给出一个比较复杂的案例，把之前在`pivot`一节中多列操作的结果（产生了多级索引），利用`wide_to_long`函数，将其转为原来的形态。其中，使用了第八章的`str.split`函数，目前暂时只需将其理解为对序列按照某个分隔符进行拆分即可。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "                                     Grade  rank\n",
       "Class Name      Subject_Examination             \n",
       "1     San Zhang Chinese_Mid             80    10\n",
       "                Chinese_Final           75    15\n",
       "                Math_Mid                90    20\n",
       "                Math_Final              85     7\n",
       "2     Si Li     Chinese_Mid             85    21\n",
       "                Chinese_Final           65    15\n",
       "                Math_Mid                92     6\n",
       "                Math_Final              88     2"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>Grade</th>\n      <th>rank</th>\n    </tr>\n    <tr>\n      <th>Class</th>\n      <th>Name</th>\n      <th>Subject_Examination</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">1</th>\n      <th rowspan=\"4\" valign=\"top\">San Zhang</th>\n      <th>Chinese_Mid</th>\n      <td>80</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>Chinese_Final</th>\n      <td>75</td>\n      <td>15</td>\n    </tr>\n    <tr>\n      <th>Math_Mid</th>\n      <td>90</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>Math_Final</th>\n      <td>85</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th rowspan=\"4\" valign=\"top\">2</th>\n      <th rowspan=\"4\" valign=\"top\">Si Li</th>\n      <th>Chinese_Mid</th>\n      <td>85</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>Chinese_Final</th>\n      <td>65</td>\n      <td>15</td>\n    </tr>\n    <tr>\n      <th>Math_Mid</th>\n      <td>92</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>Math_Final</th>\n      <td>88</td>\n      <td>2</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 19
    }
   ],
   "source": [
    "res = pivot_multi.copy()\n",
    "res.columns = res.columns.map(lambda x:'_'.join(x))\n",
    "res = res.reset_index()\n",
    "res = pd.wide_to_long(res, stubnames=['Grade', 'rank'],\n",
    "                           i = ['Class', 'Name'],\n",
    "                           j = 'Subject_Examination',\n",
    "                           sep = '_',\n",
    "                           suffix = '.+')\n",
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "   Class       Name Examination  Subject  Grade  rank\n",
       "0      1  San Zhang         Mid  Chinese     80    10\n",
       "1      1  San Zhang       Final  Chinese     75    15\n",
       "2      2      Si Li         Mid  Chinese     85    21\n",
       "3      2      Si Li       Final  Chinese     65    15\n",
       "4      1  San Zhang         Mid     Math     90    20\n",
       "5      1  San Zhang       Final     Math     85     7\n",
       "6      2      Si Li         Mid     Math     92     6\n",
       "7      2      Si Li       Final     Math     88     2"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Class</th>\n      <th>Name</th>\n      <th>Examination</th>\n      <th>Subject</th>\n      <th>Grade</th>\n      <th>rank</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Mid</td>\n      <td>Chinese</td>\n      <td>80</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Final</td>\n      <td>Chinese</td>\n      <td>75</td>\n      <td>15</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Mid</td>\n      <td>Chinese</td>\n      <td>85</td>\n      <td>21</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Final</td>\n      <td>Chinese</td>\n      <td>65</td>\n      <td>15</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Mid</td>\n      <td>Math</td>\n      <td>90</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>Final</td>\n      <td>Math</td>\n      <td>85</td>\n      <td>7</td>\n    </tr>\n    <tr>\n      <th>6</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Mid</td>\n      <td>Math</td>\n      <td>92</td>\n      <td>6</td>\n    </tr>\n    <tr>\n      <th>7</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>Final</td>\n      <td>Math</td>\n      <td>88</td>\n      <td>2</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 20
    }
   ],
   "source": [
    "res = res.reset_index()\n",
    "res[['Subject', 'Examination']] = res['Subject_Examination'].str.split('_', expand=True)\n",
    "res = res[['Class', 'Name', 'Examination', 'Subject', 'Grade', 'rank']].sort_values('Subject')\n",
    "res = res.reset_index(drop=True)\n",
    "res"
   ]
  },
  {
   "source": [
    "## 二、索引的变形\n",
    "\n",
    "### 1. stack与unstack\n",
    "\n",
    "在第二章中提到了利用`swaplevel`或者`reorder_levels`进行索引内部的层交换，下面就要讨论$\\color{red}{行列索引之间}$的交换，由于这种交换带来了`DataFrame`维度上的变化，因此属于变形操作。在第一节中提到的4种变形函数与其不同之处在于，它们都属于某一列或几列$\\color{red}{元素}$和$\\color{red}{列索引}$之间的转换，而不是索引之间的转换。\n",
    "\n",
    "`unstack`函数的作用是把行索引转为列索引，例如下面这个简单的例子："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "             col_1  col_2\n",
       "A cat big      1.0    1.0\n",
       "  dog small    1.0    1.0\n",
       "B cat big      1.0    1.0\n",
       "  dog small    1.0    1.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>col_1</th>\n      <th>col_2</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">A</th>\n      <th>cat</th>\n      <th>big</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <th>small</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">B</th>\n      <th>cat</th>\n      <th>big</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <th>small</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 21
    }
   ],
   "source": [
    "df = pd.DataFrame(np.ones((4,2)),\n",
    "                  index = pd.Index([('A', 'cat', 'big'),\n",
    "                                    ('A', 'dog', 'small'),\n",
    "                                    ('B', 'cat', 'big'),\n",
    "                                    ('B', 'dog', 'small')]),\n",
    "                  columns=['col_1', 'col_2'])\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "      col_1       col_2      \n",
       "        big small   big small\n",
       "A cat   1.0   NaN   1.0   NaN\n",
       "  dog   NaN   1.0   NaN   1.0\n",
       "B cat   1.0   NaN   1.0   NaN\n",
       "  dog   NaN   1.0   NaN   1.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">col_1</th>\n      <th colspan=\"2\" halign=\"left\">col_2</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th></th>\n      <th>big</th>\n      <th>small</th>\n      <th>big</th>\n      <th>small</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">A</th>\n      <th>cat</th>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">B</th>\n      <th>cat</th>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 22
    }
   ],
   "source": [
    "df.unstack()"
   ]
  },
  {
   "source": [
    "`unstack`的主要参数是移动的层号，默认转化最内层，移动到列索引的最内层，同时支持同时转化多个层："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "      col_1       col_2      \n",
       "        big small   big small\n",
       "A cat   1.0   NaN   1.0   NaN\n",
       "  dog   NaN   1.0   NaN   1.0\n",
       "B cat   1.0   NaN   1.0   NaN\n",
       "  dog   NaN   1.0   NaN   1.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">col_1</th>\n      <th colspan=\"2\" halign=\"left\">col_2</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th></th>\n      <th>big</th>\n      <th>small</th>\n      <th>big</th>\n      <th>small</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">A</th>\n      <th>cat</th>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">B</th>\n      <th>cat</th>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 23
    }
   ],
   "source": [
    "df.unstack(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "    col_1                  col_2                 \n",
       "        A          B           A          B      \n",
       "      big small  big small   big small  big small\n",
       "cat   1.0   NaN  1.0   NaN   1.0   NaN  1.0   NaN\n",
       "dog   NaN   1.0  NaN   1.0   NaN   1.0  NaN   1.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"4\" halign=\"left\">col_1</th>\n      <th colspan=\"4\" halign=\"left\">col_2</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">A</th>\n      <th colspan=\"2\" halign=\"left\">B</th>\n      <th colspan=\"2\" halign=\"left\">A</th>\n      <th colspan=\"2\" halign=\"left\">B</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>big</th>\n      <th>small</th>\n      <th>big</th>\n      <th>small</th>\n      <th>big</th>\n      <th>small</th>\n      <th>big</th>\n      <th>small</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>cat</th>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 24
    }
   ],
   "source": [
    "df.unstack([0,2])"
   ]
  },
  {
   "source": [
    "类似于`pivot`中的唯一性要求，在`unstack`中必须保证$\\color{red}{被转为列索引的行索引层}$和$\\color{red}{被保留的行索引层}$构成的组合是唯一的，例如把前两个列索引改成相同的破坏唯一性，那么就会报错："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "             col_1  col_2\n",
       "A cat big      1.0    1.0\n",
       "      big      1.0    1.0\n",
       "B cat big      1.0    1.0\n",
       "  dog small    1.0    1.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>col_1</th>\n      <th>col_2</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">A</th>\n      <th rowspan=\"2\" valign=\"top\">cat</th>\n      <th>big</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>big</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">B</th>\n      <th>cat</th>\n      <th>big</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <th>small</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 25
    }
   ],
   "source": [
    "my_index = df.index.to_list()\n",
    "my_index[1] = my_index[0]\n",
    "df.index = pd.Index(my_index)\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "ValueError('Index contains duplicate entries, cannot reshape')"
      ]
     },
     "metadata": {},
     "execution_count": 26
    }
   ],
   "source": [
    "try:\n",
    "    df.unstack()\n",
    "except Exception as e:\n",
    "    Err_Msg = e\n",
    "Err_Msg"
   ]
  },
  {
   "source": [
    "与`unstack`相反，`stack`的作用就是把列索引的层压入行索引，其用法完全类似。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "           A          B      \n",
       "         cat   dog  cat   dog\n",
       "         big small  big small\n",
       "index_1  1.0   1.0  1.0   1.0\n",
       "index_2  1.0   1.0  1.0   1.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">A</th>\n      <th colspan=\"2\" halign=\"left\">B</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>cat</th>\n      <th>dog</th>\n      <th>cat</th>\n      <th>dog</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th>big</th>\n      <th>small</th>\n      <th>big</th>\n      <th>small</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>index_1</th>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>index_2</th>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 27
    }
   ],
   "source": [
    "df = pd.DataFrame(np.ones((4,2)),\n",
    "                  index = pd.Index([('A', 'cat', 'big'),\n",
    "                                    ('A', 'dog', 'small'),\n",
    "                                    ('B', 'cat', 'big'),\n",
    "                                    ('B', 'dog', 'small')]),\n",
    "                  columns=['index_1', 'index_2']).T\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "                 A         B     \n",
       "               cat  dog  cat  dog\n",
       "index_1 big    1.0  NaN  1.0  NaN\n",
       "        small  NaN  1.0  NaN  1.0\n",
       "index_2 big    1.0  NaN  1.0  NaN\n",
       "        small  NaN  1.0  NaN  1.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead tr th {\n        text-align: left;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr>\n      <th></th>\n      <th></th>\n      <th colspan=\"2\" halign=\"left\">A</th>\n      <th colspan=\"2\" halign=\"left\">B</th>\n    </tr>\n    <tr>\n      <th></th>\n      <th></th>\n      <th>cat</th>\n      <th>dog</th>\n      <th>cat</th>\n      <th>dog</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">index_1</th>\n      <th>big</th>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>small</th>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">index_2</th>\n      <th>big</th>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>small</th>\n      <td>NaN</td>\n      <td>1.0</td>\n      <td>NaN</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 28
    }
   ],
   "source": [
    "df.stack()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "                     A    B\n",
       "index_1 cat big    1.0  1.0\n",
       "        dog small  1.0  1.0\n",
       "index_2 cat big    1.0  1.0\n",
       "        dog small  1.0  1.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th></th>\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">index_1</th>\n      <th>cat</th>\n      <th>big</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <th>small</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th rowspan=\"2\" valign=\"top\">index_2</th>\n      <th>cat</th>\n      <th>big</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <th>small</th>\n      <td>1.0</td>\n      <td>1.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 29
    }
   ],
   "source": [
    "df.stack([1, 2])"
   ]
  },
  {
   "source": [
    "### 2. 聚合与变形的关系\n",
    "\n",
    "在上面介绍的所有函数中，除了带有聚合效果的`pivot_table`以外，所有的函数在变形前后并不会带来`values`个数的改变，只是这些值在呈现的形式上发生了变化。在上一章讨论的分组聚合操作，由于生成了新的行列索引，因此必然也属于某种特殊的变形操作，但由于聚合之后把原来的多个值变为了一个值，因此`values`的个数产生了变化，这也是分组聚合与变形函数的最大区别。\n",
    "\n",
    "## 三、其他变形函数\n",
    "\n",
    "### 1. crosstab\n",
    "\n",
    "`crosstab`是一个地位尴尬的函数，因为它能实现的所有功能`pivot_table`都能完成。在默认状态下，`crosstab`可以统计元素组合出现的频数，即`count`操作。例如统计`learn_pandas`数据集中学校和转系情况对应的频数："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "Transfer                        N  Y\n",
       "School                              \n",
       "Fudan University               38  1\n",
       "Peking University              28  2\n",
       "Shanghai Jiao Tong University  53  0\n",
       "Tsinghua University            62  4"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Transfer</th>\n      <th>N</th>\n      <th>Y</th>\n    </tr>\n    <tr>\n      <th>School</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Fudan University</th>\n      <td>38</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>Peking University</th>\n      <td>28</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>Shanghai Jiao Tong University</th>\n      <td>53</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>Tsinghua University</th>\n      <td>62</td>\n      <td>4</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 30
    }
   ],
   "source": [
    "df = pd.read_csv('../data/learn_pandas.csv')\n",
    "pd.crosstab(index = df.School, columns = df.Transfer)"
   ]
  },
  {
   "source": [
    "这等价于如下`crosstab`的如下写法，这里的`aggfunc`即聚合参数："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "Transfer                          N    Y\n",
       "School                                  \n",
       "Fudan University               38.0  1.0\n",
       "Peking University              28.0  2.0\n",
       "Shanghai Jiao Tong University  53.0  NaN\n",
       "Tsinghua University            62.0  4.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Transfer</th>\n      <th>N</th>\n      <th>Y</th>\n    </tr>\n    <tr>\n      <th>School</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Fudan University</th>\n      <td>38.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>Peking University</th>\n      <td>28.0</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <th>Shanghai Jiao Tong University</th>\n      <td>53.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>Tsinghua University</th>\n      <td>62.0</td>\n      <td>4.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 31
    }
   ],
   "source": [
    "pd.crosstab(index = df.School, columns = df.Transfer, values = [0]*df.shape[0], aggfunc = 'count')"
   ]
  },
  {
   "source": [
    "同样，可以利用`pivot_table`进行等价操作，由于这里统计的是组合的频数，因此`values`参数无论传入哪一个列都不会影响最后的结果："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "Transfer                          N    Y\n",
       "School                                  \n",
       "Fudan University               38.0  1.0\n",
       "Peking University              28.0  2.0\n",
       "Shanghai Jiao Tong University  53.0  NaN\n",
       "Tsinghua University            62.0  4.0"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Transfer</th>\n      <th>N</th>\n      <th>Y</th>\n    </tr>\n    <tr>\n      <th>School</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Fudan University</th>\n      <td>38.0</td>\n      <td>1.0</td>\n    </tr>\n    <tr>\n      <th>Peking University</th>\n      <td>28.0</td>\n      <td>2.0</td>\n    </tr>\n    <tr>\n      <th>Shanghai Jiao Tong University</th>\n      <td>53.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>Tsinghua University</th>\n      <td>62.0</td>\n      <td>4.0</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 32
    }
   ],
   "source": [
    "df.pivot_table(index = 'School',\n",
    "               columns = 'Transfer',\n",
    "               values = 'Name',\n",
    "               aggfunc = 'count')"
   ]
  },
  {
   "source": [
    "从上面可以看出这两个函数的区别在于，`crosstab`的对应位置传入的是具体的序列，而`pivot_table`传入的是被调用表对应的名字，若传入序列对应的值则会报错。\n",
    "\n",
    "除了默认状态下的`count`统计，所有的聚合字符串和返回标量的自定义函数都是可用的，例如统计对应组合的身高均值："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "Transfer                                N       Y\n",
       "School                                           \n",
       "Fudan University               162.043750  177.20\n",
       "Peking University              163.429630  162.40\n",
       "Shanghai Jiao Tong University  163.953846     NaN\n",
       "Tsinghua University            163.253571  164.55"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th>Transfer</th>\n      <th>N</th>\n      <th>Y</th>\n    </tr>\n    <tr>\n      <th>School</th>\n      <th></th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>Fudan University</th>\n      <td>162.043750</td>\n      <td>177.20</td>\n    </tr>\n    <tr>\n      <th>Peking University</th>\n      <td>163.429630</td>\n      <td>162.40</td>\n    </tr>\n    <tr>\n      <th>Shanghai Jiao Tong University</th>\n      <td>163.953846</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>Tsinghua University</th>\n      <td>163.253571</td>\n      <td>164.55</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 33
    }
   ],
   "source": [
    "pd.crosstab(index = df.School, columns = df.Transfer, values = df.Height, aggfunc = 'mean')"
   ]
  },
  {
   "source": [
    "### 2. explode\n",
    "\n",
    "`explode`参数能够对某一列的元素进行纵向的展开，被展开的单元格必须存储`list, tuple, Series, np.ndarray`中的一种类型。"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "                            A  B\n",
       "0                      [1, 2]  1\n",
       "1                      my_str  1\n",
       "2                      {1, 2}  1\n",
       "3  0    3\n",
       "1    4\n",
       "dtype: int64  1"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>[1, 2]</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>my_str</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>{1, 2}</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0    3\n1    4\ndtype: int64</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 34
    }
   ],
   "source": [
    "df_ex = pd.DataFrame({'A': [[1, 2], 'my_str', {1, 2}, pd.Series([3, 4])],\n",
    "                      'B': 1})\n",
    "df_ex"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "        A  B\n",
       "0       1  1\n",
       "0       2  1\n",
       "1  my_str  1\n",
       "2       1  1\n",
       "2       2  1\n",
       "3       3  1\n",
       "3       4  1"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>A</th>\n      <th>B</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>0</th>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>my_str</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>1</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>4</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 35
    }
   ],
   "source": [
    "df_ex.explode('A')"
   ]
  },
  {
   "source": [
    "### 3. get_dummies\n",
    "\n",
    "`get_dummies`是用于特征构建的重要函数之一，其作用是把类别特征转为指示变量。例如，对年级一列转为指示变量，属于某一个年级的对应列标记为1，否则为0："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "   Freshman  Junior  Senior  Sophomore\n",
       "0         1       0       0          0\n",
       "1         1       0       0          0\n",
       "2         0       0       1          0\n",
       "3         0       0       0          1\n",
       "4         0       0       0          1"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Freshman</th>\n      <th>Junior</th>\n      <th>Senior</th>\n      <th>Sophomore</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0</td>\n      <td>0</td>\n      <td>0</td>\n      <td>1</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 36
    }
   ],
   "source": [
    "pd.get_dummies(df.Grade).head()"
   ]
  },
  {
   "source": [
    "## 四、练习\n",
    "### Ex1：美国非法药物数据集\n",
    "\n",
    "现有一份关于美国非法药物的数据集，其中`SubstanceName, DrugReports`分别指药物名称和报告数量："
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "   YYYY State COUNTY  SubstanceName  DrugReports\n",
       "0  2011    KY  ADAIR  Buprenorphine            3\n",
       "1  2012    KY  ADAIR  Buprenorphine            5\n",
       "2  2013    KY  ADAIR  Buprenorphine            4"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>YYYY</th>\n      <th>State</th>\n      <th>COUNTY</th>\n      <th>SubstanceName</th>\n      <th>DrugReports</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>2011</td>\n      <td>KY</td>\n      <td>ADAIR</td>\n      <td>Buprenorphine</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2012</td>\n      <td>KY</td>\n      <td>ADAIR</td>\n      <td>Buprenorphine</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2013</td>\n      <td>KY</td>\n      <td>ADAIR</td>\n      <td>Buprenorphine</td>\n      <td>4</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 37
    }
   ],
   "source": [
    "df = pd.read_csv('../data/drugs.csv').sort_values(['State','COUNTY','SubstanceName'],ignore_index=True)\n",
    "df.head(3)"
   ]
  },
  {
   "source": [
    "1. 将数据转为如下的形式：\n",
    "\n",
    "<img src=\"../source/_static/Ex5_1.png\" width=\"35%\">"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "2. 将第1问中的结果恢复为原表。\n",
    "3. 按`State`分别统计每年的报告数量总和，其中`State, YYYY`分别为列索引和行索引，要求分别使用`pivot_table`函数与`groupby+unstack`两种不同的策略实现，并体会它们之间的联系。\n",
    "\n",
    "### Ex2：特殊的wide_to_long方法\n",
    "\n",
    "从功能上看，`melt`方法应当属于`wide_to_long`的一种特殊情况，即`stubnames`只有一类。请使用`wide_to_long`生成`melt`一节中的`df_melted`。（提示：对列名增加适当的前缀）"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "   Class       Name  Chinese  Math\n",
       "0      1  San Zhang       80    80\n",
       "1      2      Si Li       90    75"
      ],
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>Class</th>\n      <th>Name</th>\n      <th>Chinese</th>\n      <th>Math</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>1</td>\n      <td>San Zhang</td>\n      <td>80</td>\n      <td>80</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>2</td>\n      <td>Si Li</td>\n      <td>90</td>\n      <td>75</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 38
    }
   ],
   "source": [
    "df = pd.DataFrame({'Class':[1,2],\n",
    "                   'Name':['San Zhang', 'Si Li'],\n",
    "                   'Chinese':[80, 90],\n",
    "                   'Math':[80, 75]})\n",
    "df"
   ]
  }
 ]
}